package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.query.resultparser.W3CParsingHandler.ElementParser;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.MyItasaShow;
import celiasoft.itasalib.structures.SubsVersion;

public class QueryMyItasaShowsResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.AllMyItasaEpisodesResultParser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {

		ArrayList<DataElement> res = new ArrayList<DataElement>();

		NodeList shows = doc.getElementsByTagName("shows");

		if (shows.getLength() < 1 || !shows.item(0).hasChildNodes()) {
			return res;
		}

		NodeList nodes = shows.item(0).getChildNodes();

		if (nodes.getLength() > 0) {
			for (int i = 0; i < nodes.getLength(); i++) {
				Node n = nodes.item(i);

				DataElement el = parseNode(n);
				if (el != null) {
					res.add(el);
				}
			}
		}

		if (res.size() > 0) {
			setMetaData(doc, meta);
		}

		return res;
	}

	private DataElement parseNode(Node n) {

		Element e = (Element) n;
		MyItasaShow el = null;

		int id = W3CParsingHandler.parseIntValue(e, "id");
		if (id != -1) {
			el = new MyItasaShow(id);
			el.setName(DomHandler.getValue(e, "name"));
			el.setVersionsOfAvailableSubs(W3CParsingHandler.parseList(e,
					"versions", new ElementParser<SubsVersion>() {

						public SubsVersion parseElement(Node n) {
							if (n != null) {
								Element e = (Element) n;
								try {
									return SubsVersion.parse(e.getTextContent());
								} catch (DOMException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (MalformedSubsVersionException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							}
							return null;
						}

					}));
		}

		return el;
	}

}
